<template>
  <div v-loading="loading">
    <el-tabs v-model="activeName">
      <el-tab-pane label="课程详情" name="first">
        <div v-if="initData.courseClassify" class="infoBox">
          <el-col :span="12">课程编号：{{ initData.courseNo }}</el-col>
          <el-col :span="12">课程名称：{{ initData.name }}</el-col>
          <el-col :span="12">课程类型：{{ getClassify(initData.courseClassify) }}</el-col>
          <el-col :span="12">课程讲师：{{ getLecturerId(initData.lecturerId) }}</el-col>
          <el-col :span="12">课程价格(元)：{{ initData.price }}</el-col>
          <el-col :span="12">课程排序：{{ initData.sort }}</el-col>
          <el-col :span="12">观看积分：{{ initData.integra }}</el-col>
          <el-col :span="12">是否上架：{{ initData.status ? "已上架" :'暂未上架' }}</el-col>
          <el-col :span="12">最低观看权限：{{ getFlag(initData.flag) }}</el-col>
          <el-col :span="12">是否首页推荐：{{ initData.recommend === true ? '已参与首页推荐' :"暂未加入首页推荐" }}</el-col>
          <el-col :span="24">
            标签：
            <el-tag
              v-for="tag in initData.label ? JSON.parse(initData.label) :[]"
              :key="tag.id"
              :style="{color:'#'+tag.color}"
              :disable-transitions="false"
              @click="pushArr(tag)"
            >{{ tag.label }}</el-tag>
          </el-col>
          <el-col :span="24">课程摘要:{{ initData.digest ?initData.digest:'暂未设置摘要' }}</el-col>
        </div>
      </el-tab-pane>
      <el-tab-pane label="课程介绍" name="second">
        <Editor
          :content="aptitudeContent"
          :category1="aptitudeContentStr"
          @submitText="submitProDetailCon"
        />
      </el-tab-pane>
      <el-tab-pane label="课程课时" name="third">
        <div v-loading="loading1" class="clearfix">
          <div class="left">
            <el-input v-model="searchInfo.keyword" type="text" placeholder="请输入内容" maxlength="20" />
          </div>
          <div class="left" style="marginLeft:5px">
            <el-button type="primary" @click="searchInfoMations">搜 索</el-button>
          </div>
          <div class="right">
            <el-button type="primary" @click="ShowAndInit">新增课时</el-button>
          </div>
        </div>
        <el-table v-if="tableData" :data="tableData" style="width: 100%">
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="address1" label="上传时间" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <span
                icon="el-icon-upload"
                type="success"
                style="margin-right: 15px;color:#67c23a;cursor:pointer"
                @click="uploadChange(scope.row)"
              >上传视频</span>
              <span
                type="primary"
                style="margin-right: 15px; color:#409eff;cursor:pointer"
                @click="editorList(scope.row)"
              >编辑</span>
              <span
                style="color:#f56c6c;cursor:pointer"
                icon="el-icon-delete"
                type="danger"
                @click="deleteList(scope.row)"
              >删除</span>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          class="right"
          :total-count="total"
          :page-size="page.pageSize"
          :current-page="page.pageNo"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        />
      </el-tab-pane>
      <el-tab-pane label="课程图片" name="four">
        <photoList :type-arr="createChildren" :data-id="$props.id" _type="课程详情" />
      </el-tab-pane>
      <!-- <el-tab-pane label="评论" name="five">定时任务补偿</el-tab-pane> -->
    </el-tabs>
    <el-dialog
      center
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :title="changePeriod ? '新增课时' :'编辑课时'"
      :visible.sync="dialogVisible"
      width="800px"
      :before-close="handleClose"
    >
      <el-form ref="formS" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题:" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="排序:" prop="sort">
          <el-input v-model="form.sort" />
        </el-form-item>
        <el-form-item label="是否免费:">
          <el-checkbox v-model="form.flag" />
        </el-form-item>
        <el-form-item label="是否上架:">
          <el-checkbox v-model="form.status" />
        </el-form-item>
        <el-form-item label="说明:">
          <Editor
            :content="form.Content"
            :show-btn="true"
            :category1="aptitudeContentStr"
            @submitText="changeAddPeriodContent"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addPeriod">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      center
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      title="上传视频"
      :visible.sync="dialogVisible1"
      width="50%"
      :before-close="handleClose1"
    >
      <div class="upload-demo">
        <div tabindex="0" class="el-upload el-upload--text">
          <el-button type="primary" @click="showSelectVideo">选择文件</el-button>
          <el-button :disabled="canUploadServer" type="success" @click="authUpload">上传到服务器</el-button>
          <input
            id="upload_video"
            ref="upload_video"
            type="file"
            name="file"
            class="el-upload__input"
            @change="changeSelectVideo"
          >
        </div>
        <ul class="el-upload-list el-upload-list--text">
          <li v-if="movie.name" tabindex="0" class="el-upload-list__item is-success">
            <a class="el-upload-list__item-name">
              <i class="el-icon-document" />
              {{ movie.name }}
            </a>
            <div
              role="progressbar"
              aria-valuenow="1"
              aria-valuemin="0"
              aria-valuemax="100"
              class="el-progress el-progress--line"
            >
              <div class="el-progress-bar">
                <div class="el-progress-bar__outer" style="height: 2px;">
                  <div class="el-progress-bar__inner" :style="{width:authProgress + '%'}" />
                </div>
              </div>
              <div class="el-progress__text" style="font-size: 12.8px;">{{ authProgress }}%</div>
            </div>
          </li>
        </ul>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose1">取 消</el-button>
        <el-button
          type="primary"
          :disabled="canSubmitVideoFile"
          @click="createUploadMessageForServe"
        >确 定</el-button>
      </span>
    </el-dialog>
    <video
      id="video_hide"
      src="movie.ogg"
      controls="controls"
      style="visibility:hidden;height:1px;width:1px;"
    >您的浏览器不支持 video 标签。</video>
  </div>
</template>

<script>
import axios from 'axios';
import mmUrl from '~/utils/utilUrl';
import { trueOrFalse } from '~/utils/util';
import regular from '~/utils/regular';
import Editor from '~/components/commom/Editor';
import Pagination from '~/components/commom/pagination';
import photoList from '~/components/commom/photoList';
import '@/lib/aliyun-oss-sdk-5.3.1.min.js';
import '@/lib/aliyun-upload-sdk-1.5.0.min.js';
export default {
  components: {
    Editor,
    Pagination,
    photoList
  },
  props: ['id'],
  data() {
    return {
      initData: {},
      CourseLecture: [],
      classifyList: [],
      levelDTOList: [],
      changePeriod: true,
      movie: {
        name: '',
        files: ''
      },
      canUploadServer: true,
      loading: true,
      loading1: true,
      canSubmitVideoFile: true,
      createChildren: [],
      rules: {
        title: regular.require50,
        sort: regular.sort
      },
      uploadTitle: '',
      uploader: null,
      aptitudeContent: '',
      dialogVisible1: false,
      activeName: 'first',
      isCreateText: true,
      isCreateText1: true,
      isCreatePeriod: true,
      aptitudeId: '',
      total: 0,
      periodId: '', // 课时ID
      textInformationId: '', // 大文本id
      aptitudeContentStr: '课程介绍',
      searchInfo: {
        courseId: this.$route.params.id,
        keyword: ''
      },
      copySearchInfo: {
        courseId: this.$route.params.id,
        keyword: ''
      },
      page: {
        maxResultCount: 0,
        pageNo: 0,
        pageSize: 10,
        skipCount: 0
      },
      dics: [],
      FileVideoId: '',
      tableData: [],
      isEditorVideoInfoMation: true,
      sureUpload: false, // 是否可以上传判断
      dialogVisible: false,
      uploadVideoInfoMation: {},
      dataId: this.$route.params.id,
      dicCode: '',
      form: {
        title: '',
        Content: '',
        sort: null,
        flag: null,
        status: null
      },
      item: {},
      authProgress: 0, // 上传进度条
      duration: 0
    }
  },
  watch: {
    activeName(newd) {
      switch (newd) {
        case 'second': {
          this.courseDescription()
          break;
        }
        case 'third': {
          this.searchInfoMations()
          break;
        }
        case 'four': {
          this.initeGetPhotoList()
          break;
        }
      }
    },
    '$props.id'() {
      this.initGetDate()
      this.activeName = 'first';
      this.getInitData()
    }
  },
  mounted() {
    this.initGetDate()
    this.getInitData()
  },
  methods: {
    getFlag(res) {
      return this.levelDTOList.some(v => v.levelCode === res)
        ? this.levelDTOList.filter(v => v.levelCode === res)[0].levelNmae
        : '';
    },
    getLecturerId(res) {
      return this.CourseLecture.some(v => v.id === res)
        ? this.CourseLecture.filter(v => v.id === res)[0].name
        : '';
    },
    getClassify(res) {
      return this.classifyList.children.some(v => v.dicCode === res)
        ? this.classifyList.children.filter(v => v.dicCode === res)[0].dicName
        : '';
    },
    getInitData() {
      this.$post({
        url: mmUrl.course.loadedit,
        data: {
          id: this.$props.id
        }
      }).then(res => {
        this.initData = res.course
        this.CourseLecture = res.CourseLecture
        this.classifyList = res.classifyList
        this.levelDTOList = res.levelDTOList
        this.loading = false
        this.showInfo = true
      })
    },
    createUploadMessageForServe() {
      this.$post({
        url: this.isEditorVideoInfoMation
          ? mmUrl.fileveideo.editor
          : mmUrl.fileveideo.createfilevideo,
        data: {
          dataType: 'VIDEO_COURSE_PERIOD',
          duration: this.duration,
          objectId: this.ObjectId,
          type: 0,
          id: this.isEditorVideoInfoMation ? this.FileVideoId : '',
          url: this.uploadVideoInfoMation.videoId,
          videoThumbailurl: '',
          fileName: this.movie.name
        }
      }).then(res => {
        this.searchInfoMations()
        this.dialogVisible1 = false
        this.canSubmitVideoFile = true
      })
    },
    initeGetPhotoList() {
      this.$post({
        url: mmUrl.course.loadcreatecourse,
        data: {
          id: this.$route.params.id
        }
      }).then(res => {
        this.createChildren = res.dicsList.filter(v =>
          v.dicCode.includes('IMAGE')
        )
        this.createChildren.forEach(v => {
          if (v.dicCode === 'IMAGE_COURSE') {
            v.dicName = '课程APP封面';
          }
        })
      })
    },
    editorList(row) {
      this.form = row
      this.changePeriod = false
      this.periodId = row.id
      this.isCreatePeriod = false
      this.form.Content = '';
      this.dialogVisible = true
      this.form.sort = row.sort
      this.form.title = row.title
      this.form.flag = row.flag === 0
      const dicCode = 'TEXTINFORMATION_COURSE_PERIOD';
      this.$post({
        url: mmUrl.text.get,
        data: {
          dataId: row.id,
          typeCode: dicCode
        }
      }).then(res => {
        if (!res.item) {
          this.isCreateText1 = true
          this.textInformationId = '';
        } else {
          this.isCreateText1 = false
          this.form.Content = res.item.content
          this.textInformationId = res.item.id
        }
      })
    },
    deleteList(res) {
      trueOrFalse(this, false).then(() => {
        this.$post({
          url: mmUrl.period.deletecourseperiod,
          data: {
            ids: [res.id]
          }
        }).then(() => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.searchInfoMations('no')
        })
      })
    },
    changeAddPeriodContent(res) {
      this.form.Content = res.text
    },
    addPeriod(res) {
      this.$refs['formS'].validate(valid => {
        if (valid) {
          const itemDate = this.isCreatePeriod
            ? {
              courseId: this.$props.id,
              title: this.form.title,
              sort: this.form.sort,
              flag: this.form.flag === true ? 0 : null,
              status: this.form.status
            }
            : {
              courseId: this.$props.id,
              title: this.form.title,
              id: this.periodId,
              sort: Number(this.form.sort),
              flag: this.form.flag === true ? 0 : null,
              status: this.form.status
            }
          this.$post({
            url: this.isCreatePeriod
              ? mmUrl.period.createcourseperiod
              : mmUrl.period.editcourseperiod,
            data: itemDate
          }).then(res => {
            this.dialogVisible = false
            let dicCode = 'TEXTINFORMATION_COURSE_PERIOD';
            const item = this.isCreateText1
              ? {
                content: this.form.Content,
                dataId: res.item.id,
                dataType: '课程管理课时详情',
                typeCode: dicCode
              }
              : {
                id: this.textInformationId,
                content: this.form.Content
              }
            this.$post({
              url: this.isCreateText1 ? mmUrl.text.create : mmUrl.text.editor,
              data: {
                item
              }
            }).then(() => {
              this.searchInfoMations()
              this.form.sort = null
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            })
          })
        }
      })
      //提交课时
    },
    uploadChange(res) {
      this.canUploadServer = true
      if (!res.videoUrl) {
        this.isEditorVideoInfoMation = false //没上传课程的话videoUrl是null
      } else {
        this.isEditorVideoInfoMation = true
      }
      this.movie = {
        name: '',
        files: ''
      }
      this.progress = 0
      this.FileVideoId = this.isEditorVideoInfoMation ? res.viderId : '';
      this.ObjectId = res.id
      this.dialogVisible1 = true
      this.uploadTitle = `${this.item.name} - ${res.title}`
      if (res.fileName) {
        this.movie.name = res.fileName
        this.authProgress = 100
      }
    },
    showSelectVideo() {
      this.$refs['upload_video'].value = '';
      document.getElementById('upload_video').click()
    },
    handleClose() {
      this.dialogVisible = false
    },
    handleClose1() {
      this.dialogVisible1 = false
      this.$refs['upload_video'].value = '';
    },
    searchInfoMations(res) {
      res === 'no' ? '' : (this.page.pageNo = 0)
      this.copySearchInfo = JSON.parse(JSON.stringify(this.searchInfo))
      this.btnSearch()
    },
    btnSearch() {
      const data = {}
      data.page = JSON.parse(JSON.stringify(this.page))
      Object.assign(data, this.searchInfo)
      data.courseId = this.$props.id
      this.$post({
        url: mmUrl.period.getcourseperiods,
        data
      }).then(res => {
        this.total = res.items.totalCount
        this.tableData = res.items.items
        this.dics = res.dics
        this.loading1 = false
      })
    },
    ShowAndInit() {
      this.changePeriod = true
      this.dialogVisible = true
      this.isCreateText1 = true
      this.form.title = '';
      this.form.Content = '';
      this.form.sort = null
      this.isCreatePeriod = true
      this.form.flag = null
    },
    courseDescription() {
      this.$post({
        url: mmUrl.text.get,
        data: {
          dataId: this.$props.id,
          typeCode: this.dicCode
        }
      }).then(res => {
        if (res.item === null) {
          this.isCreateText = true
          this.aptitudeContent = '';
          return false
        }
        this.isCreateText = false
        this.aptitudeContent = res.item.content
        this.aptitudeId = res.item.id
      })
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      let result = {}
      result.page = JSON.parse(JSON.stringify(this.page))
      Object.assign(result, this.copySearchInfo)
      this.changeTableData(result)
    },
    handleCurrentChange(val) {
      this.page.pageNo = val
      let result = {}
      result.page = JSON.parse(JSON.stringify(this.page))
      Object.assign(result, this.copySearchInfo)
      this.changeTableData(result)
    },
    changeTableData(res) {
      this.$post({
        url: mmUrl.period.getcourseperiods,
        data: res
      }).then(res => {
        this.total = res.items.totalCount
        this.tableData = res.items.items
        this.dics = res.dics
        this.loading1 = false
      })
    },
    submitProDetailCon(res) {
      // 提交课程介绍
      const item = this.isCreateText
        ? {
          content: res.text,
          dataId: this.$route.params.id,
          dataType: '课程管理详情',
          typeCode: this.dicCode
        }
        : {
          id: this.aptitudeId,
          content: res.text
        }
      this.$post({
        url: this.isCreateText ? mmUrl.text.create : mmUrl.text.editor,
        data: {
          item
        }
      }).then(() => {
        // this.ProDetailContent = res;
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.courseDescription()
      })
    },
    initGetDate() {
      this.$post({
        url: mmUrl.course.getcoursedetail,
        data: {
          id: this.$props.id
        }
      }).then(res => {
        this.item = res
        res.dicsList.forEach(v => {
          if (v.dicCode === 'TEXTINFORMATION_COURSE') {
            this.dicCode = v.dicCode
          }
        })
        this.courseDescription()
        this.loading = false
      })
    },
    changeSelectVideo(res) {
      const flag = res.target.files[0].type.includes('video')
      if (flag) {
        this.sureUpload = true
      } else {
        this.$message.error('请选择正确的视频文件')
        return false
        this.sureUpload = false
      }
      this.movie.name = res.target.files[0].name
      this.movie.files = res.target.files[0]
      this.authProgress = 0
      let files = res.target.files[0]
      let videoSrc = URL.createObjectURL(files)
      let video = document.getElementById('video_hide')
      video.src = videoSrc
      video.oncanplay = () => {
        this.duration = parseInt(video.duration)
      };
      const fileNameArr = files.name.split('.')
      let type = fileNameArr[fileNameArr.length - 1]
      this.movie.name = files.name
      this.movie.files = files
      this.uploader = this.createUploader()
      this.uploader.addFile(files, null, null, null, userData)
      let Title = files.name
      let userData = '{"Vod":{}}'
      this.canUploadServer = false
    },
    authUpload() {
      // 然后调用 startUpload 方法, 开始上传
      if (this.uploader !== null && this.sureUpload !== false) {
        this.uploader.startUpload()
      }
    },
    createUploader(type) {
      const self = this
      let uploader = new AliyunUpload.Vod({
        timeout: 60000,
        partSize: 1048576,
        parallel: 5,
        retryCount: 3,
        retryDuration: 2,
        region: 'cn-shanghai',
        userId: 1526499417634604,
        // 开始上传
        onUploadstarted: function(uploadInfo) {
          axios
            .post('/getToken', {
              Title: self.uploadTitle,
              FileName: self.movie.name
            })
            .then(res => {
              const uploadAuth = res.data.data.UploadAuth
              let uploadAddress = res.data.data.UploadAddress
              let videoId = res.data.data.VideoId
              uploader.setUploadAuthAndAddress(
                uploadInfo,
                uploadAuth,
                uploadAddress,
                videoId
              )
            })
        },
        // 文件上传成功
        onUploadSucceed: function(uploadInfo) {
          self.uploadVideoInfoMation = uploadInfo
          self.$message({
            type: 'success',
            message: '上传成功'
          })
          self.canSubmitVideoFile = false
          self.canUploadServer = true
        },
        // 文件上传失败
        onUploadFailed: function(uploadInfo, code, message) {
          self.$message.error('上传失败')
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function(uploadInfo, totalSize, progress) {
          const progressPercent = Math.ceil(progress * 100)
          self.authProgress = progressPercent
        },
        // 上传凭证超时
        onUploadTokenExpired: function(uploadInfo) {
          // // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
          // // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
          // // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
          // let refreshUrl =
          //   "https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=" +
          //   uploadInfo.videoId;
          // axios.get(refreshUrl).then(({ data }) => {
          //   let uploadAuth = data.UploadAuth;
          //   uploader.resumeUploadWithAuth(uploadAuth);
          //   console.log(
          //     "upload expired and resume upload with uploadauth " + uploadAuth
          //   );
          // });
          // self.statusText = "文件超时...";
        },
        // 全部文件上传结束
        onUploadEnd: function(uploadInfo) {
          self.$message({
            type: 'success',
            message: '文件上传完毕'
          })
        }
      })
      return uploader
    }
  }
}
</script>

<style>
</style>
